package org.zhtkj.framework.session;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

public class SessionManager {

    private static final Logger logger = LoggerFactory.getLogger(SessionManager.class.getSimpleName());
    
    private RedisTemplate<String, Object> redisTemplate;
	
    // netty生成的sessionID和Session的对应关系
    private static Map<String, Session> sessionIdMap = new ConcurrentHashMap<>();

    public SessionManager(RedisTemplate<String, Object> redisTemplate) {
    	this.redisTemplate = redisTemplate;
    }
    
    public Session findBySessionId(String id) {
        return sessionIdMap.get(id);
    }

    public Session findByTerminalId(String terminalId) {
    	Object sessionId = redisTemplate.opsForHash().get("session:" + terminalId, "sessionId");
    	if (sessionId != null) {
    		return this.findBySessionId((String) sessionId);
    	}
        return null;
    }

	public synchronized Session put(String key, Session value) {
        return sessionIdMap.put(key, value);
    }

	/**
	 * @Description: 删除session，并关闭连接
	 */
	public synchronized Session removeBySessionId(String sessionId) {
		Session session = sessionIdMap.remove(sessionId);
		if (session != null) {
			session.getChannel().close();
		}
        return session;
    }

    /**
     * @Description: 移除不活跃的session   
     */
    public void clearSession() {
    	Iterator<Entry<String, Session>> it = sessionIdMap.entrySet().iterator();
    	while (it.hasNext()) {
    		Entry<String, Session> entry = it.next();
    		if (!entry.getValue().getChannel().isActive()) {
    			logger.info("服务端移除session:{}", entry.getValue().getId());
    			removeBySessionId(entry.getKey());
    		}
    	}
    }
}